<?php
namespace plugins\goods\model;

use think\Model;
use think\Db;

/**
 * 会员模型
 */
class GoodsBrowseModel extends Model
{

    protected $open = "1"; //1开启浏览， 2.关闭浏览

    /**
     * 设置浏览量
     */
    public function setBrowseNum($uid,$gid)
    {
        if (empty($gid) || empty($uid)) {
            return zy_sys_echo(false, '未获取到数据', '', 100);
        }
        if ($this->open != 1) {
            return zy_sys_echo(false, '此此接口已被禁用', '', 101);
        }
        $time = time();
        $today = strtotime(date('y-m-d 01:00:00', $time));
        $browse = $this->get(['gid' => $gid, 'browse_time' => $today]);
        if (empty($browse)) {
            //创建
            $add = [
                'gid' => $gid,
                'browse_time' => $today,
                'browse_num' => 1,
                'uid' => '#'.$uid."#",
            ];

            $this->save($add);
        } else {
            $uid_browse = $this->get(['gid' => $gid, 'browse_time' => $today, 'uid' => ['like', $uid] ]);
            if (!$uid_browse) {
                //修改
                $upd = [
                    'browse_num' => $uid_browse['browse_num'] + 1,
                    'uid' => $uid_browse . "#".$uid."#",
                ];
                $this->save($upd,['id' => $uid_browse['id']]);
            }
        }
        return zy_sys_echo(true, '成功', '', 200);
    }

    /**
     * 获取浏览量
     */
    public function getBrowseNum( $gid , $day = 30)
    {
        if (empty($gid)) {
            return zy_sys_echo(false, '参数错误', '', 100);
        }

        $start_time = strtotime('-'.$day.'day1:0:0');

        $d = date('Y-m-d H:i:s', $start_time);
        
        $browse_num = $this->where('gid', $gid)->where('browse_time', '>=', $start_time)->sum('browse_num');

        return $browse_num;
    }






}